package com.quanxiaoha.xiaohashu.auth.sms;


import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;

import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.quanxiaoha.framework.common.util.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author: 犬小哈
 * @date: 2024/5/24 15:05
 * @version: v1.0.0
 * @description: 短信发送工具类
 **/
@Component
@Slf4j
public class AliyunSmsHelper {

    @Resource
    private AsyncClient client;

    /**
     * 发送短信（异步方式）
     * @param signName
     * @param templateCode
     * @param phone
     * @param templateParam
     * @return CompletableFuture<Boolean>
     */
    public CompletableFuture<Boolean> sendMessageAsync(String signName, String templateCode, String phone, String templateParam) {
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phone)
                .templateParam(templateParam)
                .build();

        log.info("==> 开始异步短信发送, phone: {}, signName: {}, templateCode: {}, templateParam: {}", phone, signName, templateCode, templateParam);

        // 异步发送短信
        return client.sendSms(sendSmsRequest)
                .thenApply(response -> {
                    log.info("==> 异步短信发送成功, response: {}", JsonUtils.toJsonString(response));
                    return true;
                })
                .exceptionally(error -> {
                    log.error("==> 异步短信发送错误: ", error);
                    return false;
                });
    }
}


